import { ref, onMounted, onUnmounted, type Ref } from "vue";
import { ElMessage } from "element-plus";

interface UseWebSocketOptions {
  url: string | (() => string);
  autoConnect?: boolean;
  reconnectInterval?: number;
  onMessage?: (event: MessageEvent) => void;
}

export function useWebSocket(options: UseWebSocketOptions) {
  const ws = ref<WebSocket | null>(null);
  const isConnected = ref(false);
  const reconnectTimer = ref<NodeJS.Timeout | null>(null);
  const messageQueue = ref<
    Array<{ data: string; resolve: (value: unknown) => void }>
  >([]);

  // 获取WebSocket URL（支持函数动态生成）
  const getWebSocketUrl = () => {
    return typeof options.url === "function" ? options.url() : options.url;
  };

  // 建立连接
  const connect = () => {
    // 清除之前的连接和定时器
    disconnect();

    try {
      const url = getWebSocketUrl();
      ws.value = new WebSocket(url);

      // 连接成功处理
      ws.value.onopen = () => {
        isConnected.value = true;
        ElMessage.success("WebSocket连接成功");
        clearReconnectTimer();
        flushMessageQueue();
      };

      // 消息接收处理
      ws.value.onmessage = event => {
        if (options.onMessage) {
          options.onMessage(event);
        }
      };

      // 连接关闭处理
      ws.value.onclose = () => {
        isConnected.value = false;
        ElMessage.warning("WebSocket连接已关闭");
        setupReconnectTimer();
      };

      // 错误处理
      ws.value.onerror = error => {
        ElMessage.error(`WebSocket错误: ${error.message}`);
        isConnected.value = false;
        setupReconnectTimer();
      };
    } catch (error) {
      ElMessage.error(
        `WebSocket初始化失败: ${error instanceof Error ? error.message : String(error)}`
      );
      setupReconnectTimer();
    }
  };

  // 断开连接
  const disconnect = () => {
    if (ws.value) {
      ws.value.close();
      ws.value = null;
    }
    isConnected.value = false;
    clearReconnectTimer();
  };

  // 设置重连定时器
  const setupReconnectTimer = () => {
    if (options.autoConnect !== false) {
      clearReconnectTimer();
      reconnectTimer.value = setTimeout(
        connect,
        options.reconnectInterval || 3000
      );
    }
  };

  // 清除重连定时器
  const clearReconnectTimer = () => {
    if (reconnectTimer.value) {
      clearTimeout(reconnectTimer.value);
      reconnectTimer.value = null;
    }
  };

  // 发送消息（支持队列）
  const sendMessage = (data: string): Promise<unknown> => {
    return new Promise((resolve, reject) => {
      if (isConnected.value && ws.value) {
        try {
          ws.value.send(data);
          resolve(true);
        } catch (error) {
          reject(error);
        }
      } else {
        // 连接未建立时加入队列
        messageQueue.value.push({ data, resolve });
        // 尝试连接
        if (!isConnected.value) connect();
      }
    });
  };

  // 刷新消息队列
  const flushMessageQueue = () => {
    if (isConnected.value && ws.value && messageQueue.value.length > 0) {
      messageQueue.value.forEach(({ data, resolve }) => {
        try {
          ws.value!.send(data);
          resolve(true);
        } catch (error) {
          console.error("消息发送失败:", error);
        }
      });
      messageQueue.value = [];
    }
  };

  // 组件挂载时自动连接
  onMounted(() => {
    if (options.autoConnect !== false) {
      connect();
    }
  });

  // 组件卸载时清理
  onUnmounted(() => {
    disconnect();
  });

  return {
    ws,
    isConnected,
    connect,
    disconnect,
    sendMessage
  };
}
